package devserv

import (
	"encoding/json"
	"rhelper"
)

// func onWaitKeyResp(c *Controller) {
// 	type WaitKeyResp struct {
// 		Uri     string `json:"uri"`
// 		Account string `json:"account"`
// 		Key     int    `json:"key"`
// 	}

// 	var waitKeyResp WaitKeyResp
// 	waitKeyResp.Account = c.Account
// 	waitKeyResp.Key = c.Key
// 	waitKeyResp.Uri = "/waitKey"

// 	buf, _ := json.Marshal(waitKeyResp)
// 	publishMessage(c.Id, c.Account, buf)

// }

func replyError(userServer string, cid string, errCode int, uri string) {
	type Reply struct {
		Uri string `json:"uri"`
	}

	reply := Reply{}
	reply.Uri = uri
	if reply.Uri == "/relay" {
		reply.Uri = "/runtimeInfo"
	}

	replyBuf, _ := json.Marshal(reply)

	devMsg := DevMsg{}
	devMsg.Cid = cid
	devMsg.ErrCode = errCode
	devMsg.MsgBuf = replyBuf
	buf, _ := json.Marshal(devMsg)
	publish(userServer, buf)

}

func publishMessage(userServer string, cid string, msgBuf []byte) {
	devMsg := DevMsg{}
	devMsg.Cid = cid
	devMsg.MsgBuf = msgBuf

	type errCode struct {
		Error int `json:"error"`
	}

	ec := errCode{}
	err := json.Unmarshal(msgBuf, &ec)
	if err != nil {
		devMsg.ErrCode = 0
	}

	devMsg.ErrCode = ec.Error

	buf, _ := json.Marshal(devMsg)
	publish(userServer, buf)

}

func publish(channel, value interface{}) {
	rconn := rhelper.Pool().Get()
	defer rconn.Close()
	rconn.Do("PUBLISH", channel, value)
}
